import { WEB_VIEW_PATH, ENVIRONMENT } from "@/conf/env.js";

export const getWebviewUrl = function () {
  const shareUserId = uni.getStorageSync("shareUserId");
  const initSkill = uni.getStorageSync("initSkill");
  const shareScene = uni.getStorageSync("shareScene");

  // getDebugToken  https://test.shengu.info/api/biz/ai/token?userId=65a40c25ea5afe1a54ff77b8&secret=xuhe
  if (ENVIRONMENT === "dev") {
    return `${WEB_VIEW_PATH}/ai/chat/maya?token=82526db3054480140669afc070e7d3a61bb98688&shareUserId=${shareUserId}&shareScene=${shareScene}&initSkill=${initSkill}&iswx=true`;
  }

  return `${WEB_VIEW_PATH}/ai/chat/maya?shareUserId=${shareUserId}&shareScene=${shareScene}&initSkill=${initSkill}&iswx=true`;
};

function popProperty(obj, key) {
  if (key in obj) {
    // 如果键存在于对象中，存储键对应的值
    let value = obj[key];
    // 删除该键
    delete obj[key];
    // 返回删除的键的值
    return value;
  }
  return undefined; // 如果键不在对象中，则返回 undefined
}

function toQueryString(params) {
  const encodedParams = [];

  for (let key in params) {
    if (params.hasOwnProperty(key)) {
      // 对 key 和 value 进行 URI 编码，并替换 URI 编码中的 '%20' 为 '+'，因为这是查询字符串中空格的常见表示。
      let encodedKey = encodeURIComponent(key).replace(/%20/g, "+");
      let encodedValue = encodeURIComponent(params[key]).replace(/%20/g, "+");
      encodedParams.push(encodedKey + "=" + encodedValue);
    }
  }

  // 使用 '&' 连接每一个键值对，得到完整的查询字符串
  return encodedParams.join("&");
}

export const getHomeUrl=function(){
  const app_code = uni.getStorageSync("app_code");
  console.log(app_code)
  let url='wbview'
  if(app_code){
    url=url+'?app_code='+app_code
    return url
  }
}

export const urlToObject = (url) => {
	var urlObject = {};
	if (/\?/.test(url)) {
		var urlString = url.substring(url.indexOf("?") + 1);
		var urlArray = urlString.split("&");
		for (var i = 0, len = urlArray.length; i < len; i++) {
			var urlItem = urlArray[i];
			var item = urlItem.split("=");
			urlObject[item[0]] = item[1];
		}
		return urlObject;
	}
};


// getDebugToken  https://test.shengu.info/api/biz/ai/token?userId=65a40c25ea5afe1a54ff77b8&secret=xuhe
export const h5Uri2WebviewUrl = function (url_params) {
  const path = popProperty(url_params, "path");
  const cache_app_code = uni.getStorageSync("app_code");
  console.log("cache_app_code", url_params, cache_app_code);
  const app_code = popProperty(url_params, "app_code")||cache_app_code;

  let url = WEB_VIEW_PATH + "/ai/chat/maya";

  if (path) {
    url = url + "/" + path;
  } else if (app_code == "love-ai" || app_code == "office-ai") {
    url = url + `/pages/index/${app_code}`;
  }

  if (ENVIRONMENT == "dev") {
    url_params["token"] = "82526db3054480140669afc070e7d3a61bb98688";
  }
  url_params["iswx"]="true"
  let query_string = toQueryString(url_params);
  if (query_string) {
    url = url + "?" + query_string;
  }
  console.log("h5Uri2WebviewUrl", url_params, url);
  return url;
};
